package com.ruoyi.system.service;


import com.rabbitmq.client.Channel;
import com.ruoyi.system.domain.Preferential;
import com.ruoyi.system.domain.Seckill;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RabbitListener(queues = {"Queue_Seckill"})
@Service
public class MQCouponService {

@Autowired
    IPreferentialService preferentialService;


@Autowired
    ISeckillService iSeckillService;

    @RabbitHandler
    @Transactional
    public void revMessageMap(Channel channel, Message message, Map map) throws IOException, ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        Long pid = (Long) map.get("pid");
        Long uid = (Long) map.get("uid");
        Long eid = (Long) map.get("eid");
        Preferential preferential = preferentialService.selectPreferentialByPid(pid);
        Seckill seckill = new Seckill();
        seckill.setEid(eid);
        seckill.setPid(pid);
        seckill.setUid(uid);
        seckill.setPname(preferential.getPname());
        seckill.setType(preferential.getType());
        Date parse = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
        seckill.setCreateTime(parse);
        iSeckillService.insertSeckill(seckill);
        Preferential preferential1 = new Preferential();
        preferential1.setPid(pid);
        preferential1.setPnum(preferential.getPnum()-1);
        preferentialService.updatePreferential(preferential1);
        channel.basicAck(deliveryTag,true);
    }
}
